package admin

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"outsourced-projects/pkg/communal"
	"outsourced-projects/pkg/utils"
	"outsourced-projects/service"
	"strings"
	"time"
)

type Rule struct {
	service.Base
}

func (rule Rule) Rule(c *gin.Context) {
	var err error
	//数据获取
	jsondata := make(map[string]interface{})
	err = c.BindJSON(&jsondata)
	if err != nil {
		service.ReturnJson(c, 500, err.Error(), gin.H{})
		return
	}

	db := communal.Sql()
	defer db.Close()

	data, err := db.QueryString("select * from `rule` where 1=1")
	if err != nil {
		service.ReturnJson(c, 500, err.Error(), gin.H{})
		return
	}

	service.ReturnJson(c, 200, "操作成功", gin.H{
		"list":  data,
		"total": len(data),
	})
}

func (rule Rule) SecondToHours(second int) string {
	nowtime := time.Now().Truncate(24 * time.Hour).Unix()
	newunix := nowtime + cast.ToInt64(second)
	t := time.Unix(newunix, 0).UTC()
	// 格式化时间为字符串
	str := t.Format("15:04")
	//pi := cast.ToFloat64(second) / 3600
	//s1 := fmt.Sprintf("%.2f", pi)
	return str
}

func (rule Rule) SyncRule(c *gin.Context) {
	var err error
	//数据获取
	jsondata := make(map[string]interface{})
	err = c.BindJSON(&jsondata)
	if err != nil {
		service.ReturnJson(c, 500, err.Error(), gin.H{})
		return
	}

	datas, err := utils.CheckinGetcorpcheckinoption()

	db := communal.Sql()
	defer db.Close()

	dbsession := db.NewSession()
	defer dbsession.Close()
	dbsession.Begin()

	//清除表
	_, err = dbsession.Exec(fmt.Sprint("TRUNCATE TABLE rule;"))
	if err != nil {
		service.ReturnJson(c, 500, err.Error(), gin.H{})
		return
	}

	databytes, err := json.Marshal(datas.Group)
	if err != nil {
		service.ReturnJson(c, 500, err.Error(), gin.H{})
		return
	}

	syncdata := make(map[string]interface{})
	syncdata["type"] = "rule"
	syncdata["content"] = string(databytes)
	syncdata["md5"] = ""
	syncdata["sizebig"] = ""
	syncdata["addtime"] = time.Now().Unix()
	_, err = db.Table("sync_log").Insert(syncdata)
	if err != nil {
		service.ReturnJson(c, 500, err.Error(), gin.H{})
		return
	}

	for _, v := range datas.Group {
		fmt.Println(v.Groupname)

		//正常班
		if v.Grouptype == 1 {
			ruledata := make(map[string]interface{})
			ruledata["id"] = v.Groupid
			ruledata["name"] = v.Groupname
			ruledata["type"] = v.Grouptype
			ruledata["staff_number"] = ""
			ruledata["content"] = "固定上下班<br />"
			//固定周
			for _, vv := range v.Checkindate {
				workdays := []string{}
				for _, vvv := range vv.Workdays {
					workdays = append(workdays, fmt.Sprintf("周%d", vvv))
				}
				//fmt.Println(fmt.Sprintf("上班时间（周）：%s", strings.Join(workdays, ",")))
				ruledata["content"] = fmt.Sprintf("%s%s<br />", ruledata["content"], fmt.Sprintf("上班日期：%s", strings.Join(workdays, ",")))
			}
			//固定时间
			for _, vv := range v.Checkindate {
				for _, vvv := range vv.Checkintime {
					//fmt.Println(fmt.Sprintf("======上班时间:%s", rule.SecondToHours(vvv.WorkSec)))
					//fmt.Println(fmt.Sprintf("======下班时间:%s", rule.SecondToHours(vvv.OffWorkSec)))
					ruledata["content"] = fmt.Sprintf("%s上班时间：%s<br />", ruledata["content"], rule.SecondToHours(vvv.WorkSec))
					ruledata["content"] = fmt.Sprintf("%s下班时间：%s<br />", ruledata["content"], rule.SecondToHours(vvv.OffWorkSec))
				}
			}
			_, err = dbsession.Table("rule").Insert(ruledata)
			if err != nil {
				dbsession.Rollback()
				service.ReturnJson(c, 500, err.Error(), gin.H{})
				return
			}

			fmt.Println("正常班用户")
			for _, vv := range v.Range.Userid {
				fmt.Println(vv)
			}
		}

		//排班
		if v.Grouptype == 2 {
			ruledata := make(map[string]interface{})
			ruledata["id"] = v.Groupid
			ruledata["name"] = v.Groupname
			ruledata["type"] = v.Grouptype
			ruledata["staff_number"] = ""
			ruledata["content"] = "排班上下班<br />"
			_, err = dbsession.Table("rule").Insert(ruledata)
			if err != nil {
				dbsession.Rollback()
				service.ReturnJson(c, 500, err.Error(), gin.H{})
				return
			}

			for _, vv := range v.Schedulelist {
				fmt.Println(fmt.Sprintf("======班次名称:%s", vv.ScheduleName))

				for _, vvv := range vv.TimeSection {
					fmt.Println(fmt.Sprintf("======上班时间:%s", rule.SecondToHours(vvv.WorkSec)))
					fmt.Println(fmt.Sprintf("======下班时间:%s", rule.SecondToHours(vvv.OffWorkSec)))

					fmt.Println(fmt.Sprintf("======休息时间:%s", rule.SecondToHours(vvv.RestBeginTime)))
					fmt.Println(fmt.Sprintf("======休息时间:%s", rule.SecondToHours(vvv.RestEndTime)))
				}
			}

			fmt.Println("排班用户")
			for _, vv := range v.Range.Userid {
				fmt.Println(vv)
			}
		}

		//免打卡
		if v.Grouptype == 3 {
			ruledata := make(map[string]interface{})
			ruledata["id"] = v.Groupid
			ruledata["name"] = v.Groupname
			ruledata["type"] = v.Grouptype
			ruledata["staff_number"] = ""
			ruledata["content"] = "自由上下班<br />"
			_, err = dbsession.Table("rule").Insert(ruledata)
			if err != nil {
				dbsession.Rollback()
				service.ReturnJson(c, 500, err.Error(), gin.H{})
				return
			}

			fmt.Println("免打卡用户")
			for _, vv := range v.Range.Userid {
				fmt.Println(vv)
			}
		}
	}

	dbsession.Commit()

	//所需要的数据
	service.ReturnJson(c, 200, "获取成功", gin.H{
		//"info": datas.Group,
	})
}
